package com.xy.yunduo.web.interceptor;

import com.xy.yunduo.utils.date.DateTimeUtil;
import com.xy.yunduo.utils.response.ApiException;
import com.xy.yunduo.utils.response.CommonErrorCodes;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.Enumeration;
import java.util.Map;

public class DateParamInterceptor  extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Enumeration<String> paramKeys = request.getParameterNames();
        String startDateKey=null;
        String endDateKey=null;
        Boolean isValid=false;
        //获取参数key 大小写验证 如果存在开始结束日期并记录
        while (paramKeys.hasMoreElements()) {
            String paramKey = paramKeys.nextElement();
            if(paramKey.equalsIgnoreCase("startDate")){
                startDateKey=paramKey;
                if(!isValid)
                    isValid=true;
            }
            if(paramKey.equalsIgnoreCase("endDate")){
                endDateKey=paramKey;
                if(!isValid)
                    isValid=true;
            }
        }
        //验证日期是否有效
        if (isValid) {
            try {
                Map<String, String[]> params = request.getParameterMap();
                String[] startDateVals = params.get(startDateKey);
                String[] endDateVals = params.get(endDateKey);
                if (startDateVals==null||endDateVals==null||startDateVals.length == 0 || endDateVals.length == 0) {
                    throw new ApiException(CommonErrorCodes.DATE_RANGE_PARAM_ERROR);
                }
                String startDateVal = startDateVals[0];
                String endDateVal = endDateVals[0];
                if (startDateVal.length() == 0 || endDateVal.length() == 0) {
                    throw new ApiException(CommonErrorCodes.DATE_RANGE_PARAM_ERROR);
                }
                Integer diff = DateTimeUtil.getDateDiff(startDateVal, endDateVal);
                if(diff<0||(diff+1)>12) {
                    throw new ApiException(CommonErrorCodes.DATE_RANGE_INVALID_ERROR);
                }
            } catch (ParseException e) {
                throw new ApiException(CommonErrorCodes.DATE_RANGE_INVALID_ERROR);
            }

        }
        return true;
    }

}
